#import "ImageTexturePlugin.h"
#import "ImageRender.h"

@interface ImageTexturePlugin ()

@property (nonatomic, strong) NSObject<FlutterTextureRegistry> *textures;
@property (nonatomic, strong) ImageRender *render;

@end

@implementation ImageTexturePlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"image_texture" binaryMessenger:[registrar messenger]];
    ImageTexturePlugin* instance = [[ImageTexturePlugin alloc] initWithTextures:registrar.textures];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (instancetype) initWithTextures:(NSObject<FlutterTextureRegistry> *)textures {
    if (self = [super init]) {
        _textures = textures;
    }
    return self;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([call.method isEqualToString:@"newTexture"]) {
        __block int64_t textureId = 0;
        __weak typeof(self) wself = self;
        ImageRender *render = [[ImageRender alloc] initWithImageName:@"0"];
        _render = render;
        textureId = [_textures registerTexture:render];
        
        [render renderWithCompletion:^{
            [wself.textures textureFrameAvailable:textureId];
        }];
        
        result(@(textureId));
    }
}

@end
